package cn.wolfcode.controller;

import cn.wolfcode.domain.Employee;
import cn.wolfcode.qo.EmployeeQueryObject;
import cn.wolfcode.qo.PageResult;
import cn.wolfcode.qo.QueryObject;
import cn.wolfcode.service.IDepartmentService;
import cn.wolfcode.service.IEmployeeService;
import cn.wolfcode.service.IRoleService;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
@RequestMapping("/employee")
public class EmployeeController {
    @Autowired
    private IEmployeeService employeeService;
    @Autowired
    private IDepartmentService departmentService;
    @Autowired
    private IRoleService roleService;

    @RequestMapping("/list")
    public String list(Model model, @ModelAttribute("qo") EmployeeQueryObject qo) {
        PageInfo<Employee> pageInfo = employeeService.query(qo);
        model.addAttribute("pageResult", pageInfo);

        model.addAttribute("departments", departmentService.selectAll());


        return "employee/list";
    }

    @RequestMapping("/delete")
    @ResponseBody
    public JsonResult delete(Long id) {
        try {
            employeeService.delete(id);
            return new JsonResult();
        } catch (Exception e) {
            e.printStackTrace();
            return new JsonResult(false, "删除失败");
        }
    }

    @RequestMapping("/input")
    public String input(Long id, Model model) {
        model.addAttribute("departments", departmentService.selectAll());
        model.addAttribute("roles", roleService.selectAll());

        if (id != null) {
            model.addAttribute("employee", employeeService.selectOne(id));
        }

        return "employee/input";
    }

    @RequestMapping("/saveOrUpdate")
    public String saveOrUpdate(Employee employee, Long[] ids) {
        if (employee.getId() != null) {
            employeeService.update(employee, ids);
        } else {
            employeeService.save(employee, ids);
        }
        return "redirect:/employee/list.do";
    }
}
